package com.example.dingdong.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.dingdong.daomain.BasicUserEntity;
import com.example.dingdong.repository.BasicUserRepository;
import com.example.dingdong.util.CheckUtils;



/**
 * @ClassName: MyShiroRealm
 * @Description: 登录身份验证
 * @Author :chengwenixng
 * @Copyright: Smartlab411
 * @DateTime 2021-06-15 23:08:54
 */
public class MyShiroRealm extends AuthorizingRealm {

	private static final Logger log = LoggerFactory.getLogger(MyShiroRealm.class);
	
	@Autowired
	BasicUserRepository basicUserRepository;

	 /**
     * 认证
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken authtoken = (UsernamePasswordToken) token;
		System.out.println("=>>>>>>>>"+authtoken);
		String userName = authtoken.getUsername();
		System.out.println(" userName =>>>>>>>>"+ userName );

		String password = new String(authtoken.getPassword());
		
		BasicUserEntity basicUserEntity = null;
		
		try {
			/**
			 * 手机号、账号
			 */
			basicUserEntity =basicUserRepository.findByAccountAndDelFlag(userName, true);

			if(basicUserEntity == null) {
				throw new AuthenticationException("登录信息不存在,请重新输入选择登录!");
			}
		} catch (Exception e) {
			log.error("用户登录账户信息获取失败");
			e.printStackTrace();
			throw new AuthenticationException("用户登录账户信息获取失败");
		}
		// 明文: 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, password, getName());
		return authenticationInfo;
	}
	/**
     * 授权
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		return null;
	}
}
